<?php


namespace app\home\controller;


use app\common\controller\BaseController;
use app\home\model\Member;
use app\home\model\MemberWx;
use libs\JWT;
use think\facade\Db;
use wx\WXBizDataCrypt;

class WxDecode extends BaseController
{
    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * @return \think\response\Json
     * 解密用户微信敏感数据
     */
    public function WxDecode()
    {
        // 接收参数
        $data = (array)(request()->param());
        if (empty($data)) {
            return $this->returnError(6);
        }
        $appid = config('weixin.mini_program.app_id');
        $appsecret = config('weixin.mini_program.secret');
        $grant_type = "authorization_code"; //授权（必填）
        if (empty($data['code'])) {
            return $this->returnError(26);
        }
        $code = $data['code'];        //有效期5分钟 登录会话
        $data['rawData'] = (array)($data['rawData']);
        $rawData = $data['rawData'];
        if (empty($data['rawData'])) {
            return $this->returnError(25);
        }
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?" . "appid=" . $appid . "&secret=" . $appsecret . "&js_code=" . $code . "&grant_type=" . $grant_type;
        $res = json_decode($this->httpGet($url), true);
        if (isset($res['errcode']) && ($res['errcode'] != 0)) {
            return $this->returnError(-1, [], $res['errmsg']);
        }
        $memberData = [
            'nickname' => $rawData['nickName'],
            'gender' => $rawData['gender'],
            'headimg' => $rawData['avatarUrl'],
        ];
        $count = MemberWx::where('openid', $res['openid'])->count();
        if (!empty($count)) {
            $memberWxToken['member_id'] = MemberWx::where('openid', $res['openid'])->value('member_id');
            $result['token'] = $this->jwt->encode($memberWxToken);
            return $this->returnRight($result);
        }
        //开启事务
        Db::startTrans();
        try {
            $member = Member::create($memberData);
            $memberWxData = [
                'nickname' => $rawData['nickName'],
                'openid' => $res['openid'],
                'headimgurl' => $rawData['avatarUrl'],
                'sex' => $rawData['gender'],
                'member_id' => $member->id
            ];
            $memberToken['member_id']=$member->id;
            MemberWx::create($memberWxData);
            Db::commit();
        } catch (\Exception $ex) {
            Db::rollback();
            return $this->returnException($ex);
        }
        $response['token'] = $this->jwt->encode($memberToken);
        return $this->returnRight($response);
    }
}